<script lang="ts" setup>
import { ref, onMounted } from "vue"
import { createProductsChildrenApi, updateProductsChildrenApi, getProductsChildrenDetailApi } from "@/api/products"
import { type CreateOrUpdateProductsChildrenRequestData } from "@/api/products/types"
import { type FormInstance, type FormRules, ElMessage, UploadUserFile } from "element-plus"
import { useRouter } from "vue-router"
import { CODE_SUCCESS } from "@/utils/service"
import { getBasePath, getImgApi } from "@/api/common/index"
import { computed } from "vue"
defineOptions({
  // 命名当前组件
  name: "ProductChildrenOperate"
})
const router = useRouter()
const id: string = router.currentRoute.value.params.id as string
const product_id: string = router.currentRoute.value.params.productId as string

const loading = ref<boolean>(false)

const gotoList = () => {
  router.push("/products/children")
}
//#region 增
const DEFAULT_FORM_DATA: CreateOrUpdateProductsChildrenRequestData = {
  id,
  name: "",
  icon_url: "",
  product_id,
  introduction: "",
  application_scenarios: [],
  applicable_fields: "",
  parameter_name: "",
  certificate: "",
  parameter_img_url: "",
  applicable_parts: "",
  storage: "",
  packing: "",
  number: ""
}
const formRef = ref<FormInstance | null>(null)
const formData = ref<CreateOrUpdateProductsChildrenRequestData>(JSON.parse(JSON.stringify(DEFAULT_FORM_DATA)))
const formRules: FormRules<CreateOrUpdateProductsChildrenRequestData> = {
  name: [{ required: true, trigger: "blur", message: "请输入产品名称" }],
  icon_url: [{ required: true, trigger: "blur", message: "请上传产品图标" }],
  introduction: [{ required: true, trigger: "blur", message: "请上传产品概述" }],
  application_scenarios: [{ required: true, trigger: "blur", message: "请输入产品使用场景" }],
  applicable_fields: [{ required: true, trigger: "blur", message: "请输入适用领域" }],
  parameter_name: [{ required: true, trigger: "blur", message: "请输入产品参数名" }],
  certificate: [{ required: true, trigger: "blur", message: "请输入产品证书/认证/法规" }],
  parameter_img_url: [{ required: true, trigger: "blur", message: "请上传产品参数图片" }],
  applicable_parts: [{ required: true, trigger: "blur", message: "请输入产品适用零件" }],
  storage: [{ required: true, trigger: "blur", message: "请输入产品存储/罐装/运输" }],
  packing: [{ required: true, trigger: "blur", message: "请输入产品包装" }],
  number: [{ required: true, trigger: "blur", message: "请输入产品编号" }]
}
const handleCreateOrUpdate = () => {
  formRef.value?.validate((valid: boolean, fields) => {
    if (!valid) return console.error("表单校验不通过", fields)
    loading.value = true
    const api = !formData.value.id ? createProductsChildrenApi : updateProductsChildrenApi
    api({ ...formData.value, application_scenarios: JSON.stringify(formData.value.application_scenarios) })
      .then(() => {
        ElMessage.success("操作成功")
        resetForm()
        gotoList()
      })
      .finally(() => {
        loading.value = false
      })
  })
}
const resetForm = () => {
  formRef.value?.clearValidate()
  formData.value = JSON.parse(JSON.stringify(DEFAULT_FORM_DATA))
}

//#region 查
const getProductsDetail = () => {
  if (!id) {
    return
  }
  getProductsChildrenDetailApi(id)
    .then(async ({ data }) => {
      formData.value = data
      formData.value.application_scenarios = JSON.parse(formData.value.application_scenarios)
      if (data.icon_url) {
        const { data: url } = await getImgApi({ path: data.icon_url })
        file.value = url
      }
    })
    .catch(() => {
      formData.value = DEFAULT_FORM_DATA
    })
}
const basePath = ref<string>("")
onMounted(async () => {
  getProductsDetail()
  const { data } = await getBasePath()
  basePath.value = data
})

const file = ref<any>()
const dialogImgVisible = ref<boolean>(false)
const handlePreview = async () => {
  dialogImgVisible.value = true
}

const handleParameterImgRemove = () => {
  formData.value.parameter_img_url = ""
}
const handleRemove = () => {
  formData.value.icon_url = ""
}
const handleBeforeUpload = (file: any) => {
  return new Promise((resolve, reject) => {
    const isJPG = file.type === "image/jpeg" || "image/png"
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isJPG) {
      ElMessage.error("上传图片只能是 JPG、JPEG、PNG 格式!")
      reject()
    }
    if (!isLt2M) {
      ElMessage.error("上传图片大小不能超过 2MB!")
      reject()
    }
  })
}
const handleSuccess = async (response: any) => {
  if (response.code === CODE_SUCCESS) {
    formData.value.icon_url = response.data
    const { data } = await getImgApi({ path: response.data })
    file.value = data
  }
}
const handleParameterImgSuccess = async (response: any) => {
  if (response.code === CODE_SUCCESS) {
    formData.value.parameter_img_url = response.data
  }
}

const handleImgRemove = (i: number) => {
  formData.value.application_scenarios[i].img = ""
}
const handleImgSuccess = (response: any, i: number) => {
  if (response.code === CODE_SUCCESS) {
    formData.value.application_scenarios[i].img = response.data
    formData.value.application_scenarios[i].fileList = [
      {
        name: response.data.split("/").at(-1) || "",
        url: basePath.value + response.data
      }
    ]
  }
}

const fileList = computed<UploadUserFile[]>(() => {
  let list: UploadUserFile[] = []
  if (formData.value.icon_url) {
    list = [
      {
        name: formData.value.icon_url.split("/").at(-1) || "",
        url: file.value
      }
    ]
  }
  return list
})

const parameterfileList = computed<UploadUserFile[]>(() => {
  let list: UploadUserFile[] = []
  if (formData.value.parameter_img_url) {
    list = [
      {
        name: formData.value.parameter_img_url.split("/").at(-1) || "",
        url: basePath.value + formData.value.parameter_img_url
      }
    ]
  }
  return list
})
const removeFormItem = (i: number) => {
  formData.value.application_scenarios = formData.value.application_scenarios.filter(
    (item: any, index: number) => index !== i
  )
}
const addFormItem = () => {
  formData.value.application_scenarios.push({ img: "", content: "", fileList: [] })
}
</script>

<template>
  <div class="app-container">
    <!-- 新增/修改 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>{{ id === undefined ? "新增产品" : "修改产品" }}</h3>
        </div>
      </template>
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="200px" label-position="left">
        <el-form-item prop="name" label="产品名称">
          <el-input v-model="formData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="name_en" label="产品名称(英文)">
          <el-input v-model="formData.name_en" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="number" label="产品编号">
          <el-input v-model="formData.number" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="icon_url" label="产品图标">
          <el-upload
            :file-list="fileList"
            list-type="picture-card"
            class="upload-demo"
            action="/api/uploadImg"
            :on-remove="handleRemove"
            :limit="1"
            :before-update="handleBeforeUpload"
            :on-success="handleSuccess"
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">产品图标图片不能超过 2M.</div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item prop="introduction" label="产品概述">
          <el-input v-model="formData.introduction" autosize type="textarea" />
        </el-form-item>
        <el-form-item prop="introduction_en" label="产品概述(英文)">
          <el-input v-model="formData.introduction_en" autosize type="textarea" />
        </el-form-item>
        <el-form-item prop="applicable_fields" label="适用领域">
          <el-input v-model="formData.applicable_fields" autosize type="textarea" />
        </el-form-item>
        <el-form-item prop="applicable_fields_en" label="适用领域(英文)">
          <el-input v-model="formData.applicable_fields_en" autosize type="textarea" />
        </el-form-item>
        <el-form-item prop="certificate" label="证书/认证/法规">
          <el-input v-model="formData.certificate" autosize type="textarea" />
        </el-form-item>
        <el-form-item prop="certificate_en" label="证书/认证/法规(英文)">
          <el-input v-model="formData.certificate_en" autosize type="textarea" />
        </el-form-item>
        <el-form-item label="适用场景">
          <el-button @click="addFormItem" type="primary">添加适用场景</el-button>
        </el-form-item>
        <template v-for="(formItem, i) in formData.application_scenarios" :key="i">
          <el-form-item
            prop="application_scenarios"
            :label="'适用场景' + (i + 1) + '内容'"
            :rules="{
              required: true,
              message: '请填写适用场景内容',
              trigger: 'blur'
            }"
          >
            <el-input v-model="formData.application_scenarios[i].content" />
          </el-form-item>
          <el-form-item prop="application_scenarios" :label="'适用场景' + (i + 1) + '内容(英文)'">
            <el-input v-model="formData.application_scenarios[i].content_en" />
          </el-form-item>
          <el-form-item prop="application_scenarios" :label="'适用场景' + (i + 1) + '图片'">
            <el-upload
              :file-list="formData.application_scenarios[i].fileList"
              list-type="picture-card"
              class="upload-demo"
              action="/api/uploadImg"
              :on-preview="handlePreview"
              :on-remove="() => handleImgRemove(i)"
              :limit="1"
              :before-update="handleBeforeUpload"
              :on-success="(res) => handleImgSuccess(res, i)"
            >
              <el-icon><Plus /></el-icon>
              <template #tip>
                <div class="el-upload__tip">适用场景图片不能超过 2M.</div>
              </template>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button class="mt-2" @click.prevent="removeFormItem(i)">删除</el-button>
          </el-form-item>
        </template>
        <el-form-item prop="parameter_name" label="参数名">
          <el-input v-model="formData.parameter_name" />
        </el-form-item>
        <el-form-item prop="parameter_name_en" label="参数名(英文)">
          <el-input v-model="formData.parameter_name_en" />
        </el-form-item>
        <el-form-item prop="parameter_img_url" label="参数图片地址">
          <el-upload
            :file-list="parameterfileList"
            class="upload-demo"
            list-type="picture-card"
            action="/api/uploadImg"
            :on-preview="handlePreview"
            :on-remove="handleParameterImgRemove"
            :limit="1"
            :before-update="handleBeforeUpload"
            :on-success="handleParameterImgSuccess"
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">产品参数图片不能超过 2M.</div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item prop="applicable_parts" label="适用零件">
          <el-input v-model="formData.applicable_parts" autosize type="textarea" />
        </el-form-item>
        <el-form-item prop="applicable_parts_en" label="适用零件(英文)">
          <el-input v-model="formData.applicable_parts_en" autosize type="textarea" />
        </el-form-item>
        <el-form-item prop="storage" label="存储/罐装/运输">
          <el-input v-model="formData.storage" autosize type="textarea" />
        </el-form-item>
        <el-form-item prop="storage_en" label="存储/罐装/运输(英文)">
          <el-input v-model="formData.storage_en" autosize type="textarea" />
        </el-form-item>
        <el-form-item prop="packing" label="包装">
          <el-input v-model="formData.packing" autosize type="textarea" />
        </el-form-item>
        <el-form-item prop="packing_en" label="包装(英文)">
          <el-input v-model="formData.packing_en" autosize type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="gotoList">取消</el-button>
        <el-button type="primary" @click="handleCreateOrUpdate" :loading="loading">确认</el-button>
      </template>
    </el-card>
    <el-dialog v-model="dialogImgVisible" title="图片预览" width="800" align-center>
      <img :src="file" style="width: 700px" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogImgVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
